package cn.fanyamin.dao.hibernate;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;

import cn.fanyamin.domain.Category;


public class CategoryDao extends BaseDao {
   public Category get(String categoryName) throws DaoException {
      try {
         begin();
         Query q = getSession().createQuery(
               "from Category where categoryName = :categoryName");
         q.setString("categoryName", categoryName);
         Category category = (Category) q.uniqueResult();
         commit();
         return category;
      } catch (HibernateException e) {
         rollback();
         throw new DaoException("Could not obtain the named category " + categoryName, e);
      }
   }

   public List list() throws DaoException {
      try {
         begin();
         Query q = getSession().createQuery("from Category");
         List list = q.list();
         commit();
         return list;
      } catch (HibernateException e) {
         rollback();
         throw new DaoException("Could not list the categories", e);
      }
   }

   public Category create(String categoryName) throws DaoException {
      try {
         begin();
         Category cat = new Category(categoryName);
         getSession().save(cat);
         commit();
         return null;
      } catch (HibernateException e) {
         rollback();
         throw new DaoException("Could not create the category", e);
      }
   }

   public void save(Category category) throws DaoException {
      try {
         begin();
         getSession().update(category);
         commit();
      } catch (HibernateException e) {
         rollback();
         throw new DaoException("Could not save the category", e);
      }
   }

   public void delete(Category category) throws DaoException {
      try {
         begin();
         getSession().delete(category);
         commit();
      } catch (HibernateException e) {
         rollback();
         throw new DaoException("Could not delete the category", e);
      }
   }
}
